package com.yulebaby.callsenter.observer;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;

import com.orhanobut.logger.Logger;
import com.yulebaby.callsenter.bean.CallLogBean;
import com.yulebaby.callsenter.bean.CustomerBean;
import com.yulebaby.callsenter.database.manager.Dao;
import com.yulebaby.callsenter.global.App;
import com.yulebaby.callsenter.global.Constant;
import com.yulebaby.callsenter.record.manager.AudioFileFunc;
import com.yulebaby.callsenter.task.UploadCallLogTask;
import com.yulebaby.callsenter.ui.activity.AddPreSaleRemarkActivity;
import com.yulebaby.callsenter.ui.view.CallFinishDialog;
import com.yulebaby.callsenter.utils.ThreadUtils;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Author: Zhangbo
 * Time: 2016/11/23
 * 拨号记录的内容观察者。
 */

public class CallLogObserver extends ContentObserver {

    private Uri uri = CallLog.Calls.CONTENT_URI;//等价于【Uri.parse("content://call_log/calls")】
    private ContentResolver resolver;

    public int type, duration;
    public String number;
    public long date;
    private CallFinishDialog mFinishDialog;
    private String mId;
    private String preId = "-1";
    private int i;

    public CallLogObserver() {
        super(App.mHandler);
        resolver = App.mContext.getContentResolver();
    }

    @Override
    public void onChange(boolean selfChange) {
        Observable.create((Subscriber<? super CallLogBean> subscriber) -> {
            while (true) {
                if (App.isFinish) {
                    String[] projection = new String[]{CallLog.Calls._ID, CallLog.Calls.TYPE, CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME, CallLog.Calls.DATE, CallLog.Calls.DURATION};
                    String sortOrder = CallLog.Calls.DEFAULT_SORT_ORDER;//按时间排序
                    Cursor cursor = resolver.query(uri, projection, null, null, sortOrder);
                    if (cursor != null) {
                        if (cursor.moveToFirst()) {
                            mId = cursor.getString(cursor.getColumnIndex("_id"));
                            type = cursor.getInt(cursor.getColumnIndex("type"));//通话类型，1 来电 .INCOMING_TYPE；2 已拨 .OUTGOING_；3 未接 .MISSED_
                            number = cursor.getString(cursor.getColumnIndex("number"));// 电话号码
                            String name = cursor.getString(cursor.getColumnIndex("name"));//联系人中的姓名
                            date = cursor.getLong(cursor.getColumnIndex("date"));//通话时间，即可以用getString接收，也可以用getLong接收
                            duration = cursor.getInt(cursor.getColumnIndex("duration"));//通话时长，单位：秒\
                            if (!mId.equals(preId)) {
                                CustomerBean customerBean = Dao.getInstance().queryBeanByPhone(number);
                                String Callname = customerBean == null ? "非客户号码" : customerBean.getCustomer_name();
                                long customer_id = customerBean == null ? 0 : customerBean.getCustomer_id();
                                int playState = 0;
                                String filePath = "";
                                if (duration != 0) {
                                    playState = AudioFileFunc.getAMRFilePath() == null ? 0 : 2;
                                    filePath = AudioFileFunc.getAMRFilePath() == null ? "" : AudioFileFunc.getAMRFilePath();
                                }
                                type = type == 3 ? App.mCallFlag == true ? 2 : 1 : type;
                                CallLogBean callLogBean = new CallLogBean(null, customer_id, Callname, number, date, type, duration, playState, filePath, 0);
                                Logger.d(callLogBean.getCustomer_phone() + "_mId_" + mId + "_preId_" + preId + preId.equals(mId));
                                subscriber.onNext(callLogBean);
                                subscriber.onCompleted();
                                preId = mId;
                            }
                        }
                        cursor.close();
                    }
                    break;
                }
            }
        })
                .filter(bean -> bean != null)
                .doOnNext(bean -> Dao.getInstance().insertBean(bean))
                .debounce(1000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.from(ThreadUtils.getSingleExecutor()))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CallLogBean>() {
                               @Override
                               public void onNext(CallLogBean bean) {
                                   Logger.d("测试进入次数" + i++);
                                   if (bean.getCustomer_id() != 0) {
                                       mFinishDialog = new CallFinishDialog(App.mContext, bean, () -> {
                                           Intent intent = new Intent(App.mContext, AddPreSaleRemarkActivity.class);
                                           intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                           intent.putExtra(Constant.CUSTOMER_BEAN, Dao.getInstance().queryBeanByPhone(bean.getCustomer_phone()));
                                           App.mContext.startActivity(intent);
                                           mFinishDialog.dismiss();
                                       });
                                       if (!mFinishDialog.isShowing()) {
                                           mFinishDialog.show();
                                       }
                                   }
                                   UploadCallLogTask.doUploadFiles(bean);
                               }

                               @Override
                               public void onCompleted() {
                                   initParams();
                               }

                               @Override
                               public void onError(Throwable e) {
                                   initParams();
                                   Logger.d(e.getLocalizedMessage());
                               }
                           }
                );
    }

    private void initParams() {
        mId = "";
        type = -1;
        duration = 0;
        number = "";
        date = 0l;
        App.isFinish = false;
        App.mCallFlag = false;
    }
}
